﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HugMe.Bussiness;
using HugMe.Bussiness.Model;
using HugMe.Bussiness.Model.vk;

namespace HugMe.Controllers
{
	public class VkController : Controller
	{
		Func<HttpRequestBase,string> getUserId = (request) =>
			                                         {
				                                         string userId = "viewer_id";//"user_id";
				                                     string meId = request.Params[userId];
																						 if (string.IsNullOrWhiteSpace(meId))
																						 {
																							 meId = request.Cookies[Vk.VkUserIdCookie] != null ? request.Cookies[Vk.VkUserIdCookie].Value : string.Empty;
																						 }

																						 meId = (meId ?? string.Empty).Split(',')[0];
#if DEBUG
/*
				                                     if (string.IsNullOrWhiteSpace(meId))
					                                     meId = "176936922";
*/
#endif
																						 return meId;
			                                     };

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var request = filterContext.HttpContext.Request;
			string userId = "viewer_id";//"user_id";
			var meId = request.Params[userId];
			if (!string.IsNullOrWhiteSpace(meId))
				filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(Vk.VkUserIdCookie, meId.Split(',')[0]));

			base.OnActionExecuting(filterContext);
		}

		public ActionResult Index(int page)
		{
			page = page < 1 ? 1 : page;
			ViewBag.CurrentPage = page;
			string userId = getUserId(Request);
			var model = Vk.GetFriends(userId, page) ?? new Person[0];

			var countObj = VkPerson.GetStatuses(userId, model);

			if (countObj is int)
				ViewBag.MessageCount = (int)countObj;
			else
				ViewBag.MessageCount = 0;

			return View(model);
		}

		[HttpPost]
		public ActionResult AddPartner(string partnerId)
		{
			var result = VkPerson.Get(getUserId(Request), partnerId);
			return Json(new {result = result});
		}

		public ActionResult ViewMessages()
		{
			List<Person> model = VkPerson.CompleteList(getUserId(Request));

			Vk.FillPartners(model);

			return View(model);
		}

		public ActionResult Approve(string partnerId)
		{
			VkPerson.Approve(getUserId(Request),partnerId);

			return Json(new {}, JsonRequestBehavior.AllowGet);
		}

	}
}
